// pages/workbench/workbench.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navHeadHeight: 0,
    navHeight: 0,
    avatar: '/static/images/personal/index/avatar.png',
    userInfo: {},
    appletMenuList: [],
    // referralItems: [{
    //     url: '/pages/appointmentReferral/add/add',
    //     icon: "/static/images/workbench/icon_1001.png",
    //     text: "预约转诊"
    //   },
    //   {
    //     url: '/pages/referralService/list/list',
    //     icon: "/static/images/workbench/icon_1002.png",
    //     text: "转诊管理"
    //   },
    //   {
    //     url: '/pages/appointmentReferral/order/list/list',
    //     icon: "/static/images/workbench/icon_1003.png",
    //     text: "预约订单"
    //   },
    //   {
    //     url: '/pages/cancellation/list/list',
    //     icon: "/static/images/workbench/icon_1004.png",
    //     text: "取消预约"
    //   }
    // ],
    equipmentServices: [{
        url: '/pages/equipment/configuration/configuration',
        icon: "/static/images/workbench/icon_1001_c.png",
        text: "设备发放",
        desc: '选择搭配服务项目，充值设备',
        type: 1
      },
      {
        url: '/pages/equipment/order/detail/going/going?type=equipmentReturnds',
        icon: '/static/images/workbench/icon_1002_c.png',
        text: '设备归还',
        desc: '归还使用设备，结束服务项目',
        type: 1
      },
      {
        url: '/pages/equipment/order/list/list',
        icon: "/static/images/workbench/icon_1003_c.png",
        text: "设备订单",
        desc: '查看历史发放设备相关订单信息',
        type: 1
      },
      {
        url: '/pages/equipment/order/filter/filter',
        icon: "/static/images/workbench/icon_1001_c.png",
        text: "扫码发放设备",
        desc: '扫码用户已购买服务项目二维码',
        type: 0
      },
      {
        url: '/pages/equipment/order/detail/going/going?type=equipmentReturnds',
        icon: "/static/images/workbench/icon_1002_c.png",
        text: "自购服务设备归还",
        desc: '归还使用设备，结束服务项目',
        type: 0
      },
      {
        url: '/pages/equipment/order/list/list?type=zgfw',
        icon: "/static/images/workbench/icon_1003_c.png",
        text: "自购服务订单",
        desc: '查看历史发放设备相关订单信息',
        sum: 100,
        type: 0
      },
      {
        url: '/pages/equipment/management/index/index',
        icon: "/static/images/workbench/icon_1004_c.png",
        text: "设备管理",
        desc: '查看库存闲置设备、出租逾期设备'
      },
      {
        url: '/pagesA/sjstatistics/sjstatistics',
        icon: "/static/images/workbench/icon_1005_c.png",
        text: "数据统计",
        desc: '机构、科室、人员工作量数据统计'
      },
      {
        url: '/pagesA/jgstatistics/jgstatistics',
        icon: "/static/images/workbench/icon_1006_c.png",
        text: "机构数据",
        desc: '账号关联机构数据统计',
        type: 0
      },
    ],
    isLock:null,
    hospInfo:null,
    isShowcus:false,
    custom:''
    // dataStatistics: [{
    //     url: '',
    //     icon: "/static/images/workbench/icon_3001.png",
    //     text: "医院运营"
    //   },
    //   {
    //     url: '',
    //     icon: "/static/images/workbench/icon_3002.png",
    //     text: "医护绩效"
    //   },
    // ]
  },
  onLoad() {
    let that = this
    //获取手机设备情况
    let headHeight = 0
    wx.getSystemInfo({
      success: (res) => {
        headHeight = res.statusBarHeight
      }
    })
    // 获取胶囊坐标位置
    const res = wx.getMenuButtonBoundingClientRect()
    let menuInfoTop = res.top
    let menuInfoBottom = res.bottom
    this.setData({
      // navHeadHeight:(menuInfoTop+menuInfoBottom-headHeight)*2+'rpx',
      navHeadHeight: (res.top) * 2 + 'rpx',
      navHeight: (res.height * 2) + 'rpx'
    })
    this.getUser()
  },
  onShow(){
    let that = this
    this.setData({
      isLock:null
    })
    if(wx.getStorageSync('deviceId')){
      wx.closeBLEConnection({
        deviceId: wx.getStorageSync('deviceId'),
        success(res) {
          wx.removeStorageSync('deviceId')
        },
        fail(res) {
        }
      })
    }
  　wx.closeBluetoothAdapter({
      success(res){
      },
      fail(res){
      }
    })
    setTimeout(()=>{
      app.getHost(app.globalData.userInfo.hospitalId).then(res => {
        if(wx.getStorageSync('isShowcus')==1){
          that.setData({
            isShowcus:false
          })
        }else{
          that.setData({
            hospInfo: res,
            isShowcus:res.settlementUnit==2?(res.availableHours<30?true:false):(res.availableDays<30?true:false),
            custom:res.settlementUnit==2?'时间':'天数'
          })
        }
        if(res.settlementUnit==2 && res.availableHours>=30){
            wx.removeStorageSync('isShowcus')
        }else if(res.availableDays>=30){
          wx.removeStorageSync('isShowcus')
        }
      })
    },200)
  },
  
  /**
   * 用户点击跳转页面
   */
  getUser: function () {
    let that = this
    app.getUserInfo().then(res => {
      if (res.code == 5009) {
        wx.removeStorageSync('token')
        wx.removeStorageSync('token1')
        return wx.reLaunch({
          url: '/pages/login/login',
        })
      }else{
        that.setData({
          userInfo: res
        })
        wx.request({
          url: app.globalData.serverUrl + '/applet/list/' + that.data.userInfo.deptId,
          method: 'GET',
          header: {
            'token': wx.getStorageSync('token')
          },
          success: (res => {
            let resData = res.data
            if (resData.code == 200) {
              that.setData({
                appletMenuList: that.fiterFun(resData.data.appletMenuList)
              })
            }
          })
        })
      }
    })
  },
  hideDialog(){
    this.setData({
      isShowcus:false
    })
    wx.setStorageSync('isShowcus', 1)
  },
  fiterFun: function (dataArr) {
    let arr = []
    let endArr = []
    dataArr.map(item => {
      this.data.equipmentServices.map(v => {
        if (item.appletMenuName == v.text) {
          v.id = item.appletId
          arr.push(v)
        }
      })
    })
    arr.map(item => {
      if (this.data.userInfo.permission.appletIdList.some(x => {
          return x == item.id
        })) {
        endArr.push(item)
      }
    })
    return arr
  },
  showDialog({
    title,
    tip,
    icon
  } = {}) {
    this.setData({
      title: title,
      tip: tip,
      icon: icon
    })
    this.selectComponent('#dialog').show()
  },
  showDialogsq({
    title,
    tip,
    icon
  } = {}) {
    this.setData({
      title: title,
      tip: tip,
      icon: icon
    })
    this.selectComponent('#dialogsq').show()
  },
  colsFun() {
    wx.navigateBack({
      delta: 1,
    })
  },
  shouquan() {
    wx.openSetting()
  },
  onPullDownRefresh() {
    this.getUser()
    wx.stopPullDownRefresh()
  },
  toPage(e) {
    let that = this
    let lock=null
    if(!that.data.isLock){
      that.setData({
        isLock:new Date().getTime()
      })
    }else{
      lock = new Date().getTime()
    }
    if(that.data.isLock && lock){
      if(lock-that.data.isLock<app.globalData.isNumLock){
        return
      }else{
        that.setData({
          isLock:lock
        })
      }
    }
    const text = e.currentTarget.dataset.text
    const url = e.currentTarget.dataset.url
    if (text == '设备发放' || text == '设备归还'  || text=='自购服务设备归还' || text=='设备订单' || text=='自购服务订单') {
      wx.getSystemInfo({
        success(resd) {
          let locationEnabled = resd.locationEnabled; //判断手机定位服务是否开启
          let locationAuthorized = resd.locationAuthorized; //判断定位服务是否允许微信授权
          let bluetoothEnabled = resd.bluetoothEnabled; //判断蓝牙服务是否开启
          
          if (!locationEnabled) {
            that.showDialog({
              title: '手机未打开定位功能',
              icon: 'fail',
              tip: ['']
            })
          } else if (!locationAuthorized) {
            that.showDialog({
              title: '微信未授权定位权限',
              icon: 'fail',
              tip: ['请前往设置-应用内打开', '微信定位信息权限']
            })
          } else if(!bluetoothEnabled){
            that.showDialog({
              title: '手机蓝牙未打开',
              icon: 'fail',
              tip: ['请前往设置-应用内打开', '手机蓝牙']
            })
          }
          else {
            wx.getSetting({
              success: res => {
                console.log(res);
                let authSetting = res.authSetting
                if (authSetting['scope.userLocation']) {
                  if(authSetting['scope.bluetooth'] == undefined){
                    wx.authorize({
                      scope: 'scope.bluetooth',
                      success(resp) {
                        console.log(resp);
                        if (resp.errMsg == "authorize:ok") {
                          wx.navigateTo({
                            url: url,
                          })
                        }
                      }
                    })
                  }else{
                    if (authSetting['scope.bluetooth']) {
                      wx.navigateTo({
                        url: url,
                      })
                    } else {
                      that.showDialogsq({
                        title: '请给予蓝牙权限',
                        icon: 'warning',
                        tip: ['']
                      })
                    }
                  }
                  
                } else {
                  that.showDialogsq({
                    title: '请给予微信定位权限',
                    icon: 'warning',
                    tip: ['']
                  })
                }
              }
            })
          }
        },
        fail() {
          that.showDialog({
            title: '手机未打开定位功能',
            icon: 'fail',
            tip: ['']
          })
        }
      })
      return
    }
    // if (text == '设备归还' || text=='扫码发放设备' || text=='自购服务设备归还') {
    //   return wx.scanCode({
    //     success(res) {
    //       wx.navigateTo({
    //         url: url+(text=='自购服务设备归还'?'&codeId='+encodeURIComponent(res.result):'?codeId='+encodeURIComponent(res.result)),
    //       })
    //     }
    //   })
    // }
    if (text == '扫码发放设备') {
      wx.getSystemInfo({
        success(resd) {
          let locationEnabled = resd.locationEnabled; //判断手机定位服务是否开启
          let locationAuthorized = resd.locationAuthorized; //判断定位服务是否允许微信授权
          let bluetoothEnabled = resd.bluetoothEnabled; //判断蓝牙服务是否开启
          if (locationEnabled == false) {
            that.showDialog({
              title: '手机未打开定位功能',
              icon: 'fail',
              tip: ['']
            })
          } else if (locationAuthorized == false) {
            that.showDialog({
              title: '微信未授权定位权限',
              icon: 'fail',
              tip: ['请前往设置-应用内打开', '微信定位信息权限']
            })
          } else if(bluetoothEnabled == false){
            that.showDialog({
              title: '手机蓝牙未打开',
              icon: 'fail',
              tip: ['请前往设置-应用内打开', '手机蓝牙']
            })
          }
          else {
            wx.getSetting({
              success: res => {
                console.log(res);
                let authSetting = res.authSetting
                if (authSetting['scope.userLocation']) {
                  console.log(authSetting);
                  if(authSetting['scope.bluetooth'] == undefined){
                    wx.authorize({
                      scope: 'scope.bluetooth',
                      success(resp) {
                        console.log(resp);
                        if (resp.errMsg == "authorize:ok") {
                          wx.scanCode({
                            onlyFromCamera: true,
                            success:restd=>{
                              wx.navigateTo({
                                url: url + '?codeId=' + encodeURIComponent(restd.result),
                              })
                            }
                          })
                        }
                      }
                    })
                  }else if(authSetting['scope.bluetooth']){
                    wx.scanCode({
                      onlyFromCamera: true,
                      success:restd=>{
                        wx.navigateTo({
                          url: url + '?codeId=' + encodeURIComponent(restd.result),
                        })
                      }
                    })
                    
                  }else{
                    that.showDialogsq({
                      title: '请给予蓝牙权限',
                      icon: 'warning',
                      tip: ['']
                    })
                  }
                } else {
                  that.showDialogsq({
                    title: '请给予微信定位权限',
                    icon: 'warning',
                    tip: ['']
                  })
                }
              }
            })
          }
        },
        fail() {
          that.showDialog({
            title: '手机未打开定位功能',
            icon: 'fail',
            tip: ['']
          })
        }
      })
      return
    }
    wx.navigateTo({
      url: url,
    })
  }
})